<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>落地页管理</span>
      </div>
      <!-- 搜索表单 -->
      <el-form
        :model="where"
        class="ele-form-search"
        label-width="60px"
        @keyup.enter.native="reload"
        @submit.native.prevent
      >
        <div class="app-container">
          <div class="filter-container">
            <el-select
              v-model="where.bazaar"
              class="filter-item"
              clearable
              placeholder="请选择推广市场"
              @change="reload"
            >
              <el-option
                v-for="item in bazaarList"
                :key="item.id"
                :disabled="item.status === 0"
                :label="
                  `[` +
                  [
                    '',
                    '百度SEM竞价',
                    '百度信息流',
                    '巨量引擎',
                    '搜狗推广',
                    '卧龙推广',
                    '360点睛',
                  ][item.platform] +
                  `] ` +
                  item.name
                "
                :value="item.id"
              />
            </el-select>

            <el-input
              v-model="where.SiteName"
              class="filter-item"
              clearable
              placeholder="站点名称"
              style="width: 180px"
              @clear="reload"
            />

            <el-input
              v-model="where.DomainUrl"
              class="filter-item"
              clearable
              placeholder="落地页"
              style="width: 180px"
              @clear="reload"
            />

            <el-button
              class="filter-item"
              icon="el-icon-search"
              type="primary"
              @click="reload"
              >搜索
            </el-button>

            <el-button
              class="filter-item"
              icon="el-icon-refresh"
              style="margin-left: 2px"
              @click="reset"
              >重置
            </el-button>
          </div>
        </div>
      </el-form>

      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="url"
        :max-height="defaultHeight"
        :selection.sync="selection"
        :where="where"
      >
        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <el-button
            v-if="$hasPermission('website:save')"
            icon="el-icon-plus"
            size="small"
            type="primary"
            @click="openEdit({})"
            >添加
          </el-button>
          <el-button
            v-if="$hasPermission('website:delete')"
            icon="el-icon-delete"
            size="small"
            type="danger"
            @click="removeBatch"
            >删除
          </el-button>
        </template>

        <!-- 落地页列 -->
        <template slot="DomainUrl" slot-scope="{ row }">
          <el-link :href="`http://` + row.DomainUrl" target="_blank">{{
            format(row.DomainUrl, 20)
          }}</el-link>
        </template>

        <!-- 推广市场列 -->
        <template slot="bazaar" slot-scope="{ row }">
          <template v-for="item in bazaarList">
            <span v-if="item.id === row.bazaar" :key="item.id">
              {{ item.name }}
            </span>
          </template>
        </template>

        <!-- 展示模式列 -->
        <template slot="SiteModel" slot-scope="{ row }">
          <el-tag
            v-if="!row.SiteModel"
            effect="plain"
            size="mini"
            type="success"
          >
            随市场展示
          </el-tag>

          <template v-for="item in modelList">
            <el-tag
              v-if="item.value === row.SiteModel"
              :key="item.value"
              :disable-transitions="true"
              :type="['', 'success', 'info'][row.SiteModel]"
              size="mini"
            >
              {{ item.label }}
            </el-tag>
          </template>
        </template>

        <!-- AB页状态列 -->
        <template slot="abswitch" slot-scope="{ row }">
          <el-tag :type="['info', 'success'][row.abswitch]" size="mini">
            {{ ["未开启AB页", "已开启AB页"][row.abswitch] }}
          </el-tag>
        </template>

        <!-- 百度统计列 -->
        <template slot="BaiduCode" slot-scope="{ row }">
          <el-tag v-if="!row.BaiduCode" size="mini" type="info">未设置</el-tag>
          <el-tag v-if="row.BaiduCode" size="mini" type="success"
            >已设置</el-tag
          >
        </template>

        <!-- 自助恢复列 -->
        <template slot="SiteSource" slot-scope="{ row }">
          <el-tag v-if="!row.isSiteSource" size="mini" type="info"
            >未上传</el-tag
          >
          <el-tag v-if="row.isSiteSource" size="mini" type="success"
            >已上传</el-tag
          >
        </template>

        <!-- 宝塔状态列 -->
        <template slot="btAddress" slot-scope="{ row }">
          <el-tag v-if="!row.btAddress || !row.btKey" size="mini" type="info"
            >未设置</el-tag
          >
          <el-tag v-if="row.btAddress && row.btKey" size="mini" type="success"
            >已设置</el-tag
          >
        </template>

        <!-- 落地页列 -->
        <template slot="url" slot-scope="{ row }">
          <el-tag v-if="!row.url" size="mini" type="info">未设置</el-tag>
          <el-tag v-if="row.url" size="mini" type="success">已设置</el-tag>
        </template>

        <!-- 绑定域名列 -->
        <template slot="Domains" slot-scope="{ row }">
          <el-tag v-if="!row.Domains" size="mini" type="info">未设置</el-tag>
          <el-tag v-if="row.Domains" size="mini" type="success">已设置</el-tag>
        </template>

        <!-- 状态列 -->
        <template slot="status" slot-scope="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="1"
            :inactive-value="0"
            @change="editState(row)"
          />
        </template>

        <!-- 操作列 -->
        <template slot="action" slot-scope="{ row }">
          <el-link
            v-if="$hasPermission('website:update')"
            :underline="false"
            icon="el-icon-edit-outline"
            type="success"
            @click="openEdit(row)"
            >修改
          </el-link>
          <el-popconfirm
            class="ele-action"
            title="确定要删除此用户吗？"
            @confirm="remove(row)"
          >
            <el-link
              v-if="$hasPermission('website:delete')"
              slot="reference"
              :underline="false"
              icon="el-icon-delete"
              type="danger"
              >删除
            </el-link>
          </el-popconfirm>

          <el-link
            v-if="$hasPermission('website:update')"
            slot="reference"
            :underline="false"
            @click="abPage(row)"
            icon="el-icon-setting"
            type="primary"
            >AB页操作
          </el-link>
        </template>
      </ele-pro-table>
    </el-card>
    <!-- 编辑弹窗 -->
    <vue-edit
      :data="current"
      :visible.sync="showEdit"
      @childFn="getBazaarList"
      @done="reload"
    />

    <el-dialog
      :title="
        `【` +
        abEditData.SiteName +
        ' - ' +
        abEditData.DomainUrl +
        `】AB页在线切换`
      "
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :lock-scroll="false"
      :visible.sync="AbDialogVisible"
      width="800px"
    >
      <div>
        <el-radio v-model="abRadio" :label="1" @change="abchange"
          >关闭AB页</el-radio
        >
        <el-radio v-model="abRadio" :label="2" @change="abchange"
          >开启AB页</el-radio
        >
      </div>

      <div style="margin-top: 15px">
        <el-select
          v-if="abRadio == 2"
          v-model="nginxValue"
          class="ele-block"
          clearable
          multiple
          placeholder="请选择Nginx配置"
          @change="nginxChanged"
        >
          <el-option
            v-for="item in nginxList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <div style="margin-top: 15px"></div>

        <el-input
          v-model="nginxText"
          ref="nginxText"
          :readonly="true"
          :rows="16"
          type="textarea"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="AbDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="nginxSave" :loading="nginxLoading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import VueEdit from "./vue-edit";

export default {
  name: "siteWebsite",
  components: { VueEdit },
  data() {
    return {
      // 表格高度
      defaultHeight: 0,
      // 展示模式
      modelList: [
        { value: 1, label: "均衡展示" },
        { value: 2, label: "随机展示" },
        { value: 3, label: "权重展示" },
        { value: 4, label: "轮番展示" },
      ],
      // 表格数据接口
      url: "/website/read",
      // 表格列配置
      columns: [
        {
          columnKey: "selection",
          type: "selection",
          width: 45,
          align: "center",
        },
        {
          columnKey: "index",
          type: "index",
          width: 60,
          label: "序号",
          align: "center",
          showOverflowTooltip: true,
        },
        {
          columnKey: "bazaar",
          label: "推广市场",
          showOverflowTooltip: true,
          slot: "bazaar",
        },
        {
          prop: "SiteName",
          label: "站点名称",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "DomainUrl",
          label: "落地页",
          sortable: "custom",
          showOverflowTooltip: true,
          slot: "DomainUrl",
        },
        {
          columnKey: "url",
          label: "URL地址",
          sortable: "custom",
          showOverflowTooltip: true,
          slot: "url",
        },
        {
          columnKey: "Domains",
          label: "绑定域名",
          sortable: "custom",
          showOverflowTooltip: true,
          slot: "Domains",
        },
        {
          prop: "SiteModel",
          label: "展示模式",
          sortable: "custom",
          showOverflowTooltip: true,
          slot: "SiteModel",
        },
        {
          columnKey: "abswitch",
          label: "AB页状态",
          sortable: "custom",
          showOverflowTooltip: true,
          slot: "abswitch",
        },
        {
          columnKey: "SiteSource",
          label: "站点源码",
          sortable: "custom",
          showOverflowTooltip: true,
          slot: "SiteSource",
        },
        {
          columnKey: "btAddress",
          label: "宝塔状态",
          sortable: "custom",
          showOverflowTooltip: true,
          slot: "btAddress",
        },
        {
          columnKey: "BaiduCode",
          label: "百度统计",
          sortable: "custom",
          showOverflowTooltip: true,
          slot: "BaiduCode",
        },
        {
          prop: "Copyright",
          label: "站点版权",
          sortable: "custom",
          showOverflowTooltip: true,
        },
        {
          prop: "datatime",
          label: "创建时间",
          sortable: "custom",
          showOverflowTooltip: true,
          formatter: (row, column, cellValue) => {
            return this.$util.toDateString(cellValue);
          },
        },
        {
          prop: "status",
          label: "状态",
          width: 80,
          sortable: "custom",
          resizable: false,
          slot: "status",
        },
        {
          columnKey: "action",
          label: "操作",
          width: 200,
          resizable: false,
          slot: "action",
          fixed: "right",
        },
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 市场列表
      bazaarList: [],
      // 是否显示编辑弹窗
      showEdit: false,
      // 是否显示AB页
      AbDialogVisible: false,
      abEditData: {},
      abRadio: 1,
      nginxValue: [0],
      nginxList: [
        { value: 0, label: "开启检测百度APP（必须是百度app打开才看到真）" },
        { value: 1, label: "开启检测微信（微信打开看到真）" },
        { value: 2, label: "开启检测BD_VID（不管怎么打开只要带vid看到真）" },
      ],
      aPage: "",
      bPage: "",
      // 表单数据
      nginxText: "",
      nginxLoading: false,
    };
  },
  created() {
    window.addEventListener("resize", this.getHeight);
    this.getHeight();
  },

  methods: {
    /*设置表格高度*/
    getHeight() {
      this.defaultHeight = window.innerHeight - 360;
    },

    /* 落地页格式化 */
    format(value, limit) {
      if (!value) return "";
      if (value.length > limit) {
        return value.slice(0, limit) + "...";
      }
      return value;
    },
    /* 获取角色组 */
    getBazaarList(data) {
      this.bazaarList = data;
    },
    /* 刷新表格 */
    reload(isPage) {
      let obj = { where: this.where };
      if (!isPage) {
        obj.page = 1;
      }
      this.$refs.table.reload(obj);
    },

    /* 重置搜索 */
    reset() {
      for (let key in this.where) {
        this.where[key] = null;
      }
      this.reload();
    },
    /* 显示编辑 */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },
    /* 删除 */
    remove(row) {
      const loading = this.$loading({ lock: true });
      this.$http
        .delete("/website/delete/id/" + row.id)
        .then((res) => {
          loading.close();
          if (res.data.code === 0) {
            this.$message.success(res.data.msg);
            this.reload();
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((e) => {
          loading.close();
          this.$message.error(e.message);
        });
    },
    /* 批量删除 */
    removeBatch() {
      if (!this.selection.length) {
        this.$message.error("请至少选择一条数据");
        return;
      }
      this.$confirm("确定要删除选中的用户吗?", "提示", {
        type: "warning",
      })
        .then(() => {
          const iad = this.selection.map((d) => d.id);
          const loading = this.$loading({ lock: true });
          this.$http
            .delete("/website/delete", {
              data: { id: iad.join(",") },
            })
            .then((res) => {
              loading.close();
              if (res.data.code === 0) {
                this.$message({ type: "success", message: res.data.msg });
                this.reload();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((e) => {
              loading.close();
              this.$message.error(e.message);
            });
        })
        .catch(() => {});
    },
    /* 更改状态 */
    editState(row) {
      const loading = this.$loading({ lock: true });
      this.$http
        .put("/website/update/state/" + row.id, { status: row.status })
        .then((res) => {
          loading.close();
          if (res.data.code === 0) {
            this.$message({ type: "success", message: res.data.msg });
          } else {
            row.state = !row.state ? 1 : 0;
            this.$message.error(res.data.msg);
          }
        })
        .catch((e) => {
          loading.close();
          this.$message.error(e.message);
        });
    },

    abPage(row) {
      this.abRadio = 1;
      this.abEditData = row;
      this.nginxValue = [0];
      this.nginxText =
        "#access_page begin tag\n" +
        "root " +
        row.aPage +
        ";\n" +
        "#access_page end tag\n";
      this.AbDialogVisible = true;
    },

    nginxChanged(obj) {
      const arr = [
        "# 如果未检测到百度APP特征码返回假\n" +
          'if ($http_user_agent !~* "baiduboxapp") {\n' +
          "\tset $http_allow_flag 0;\n" +
          "}\n",
        "# 如果检测到微信特征码返回真\n" +
          'if ($http_user_agent ~* "micromessenger") {\n' +
          "\tset $http_allow_flag 1;\n" +
          "}\n",
        "# 如果未检测到百度VID返回假\n" +
          'if ($query_string !~* "bd_vid=") {\n' +
          "\tset $http_allow_flag 0;\n" +
          "}\n",
      ];
      let array = [];
      let template =
        "#access_page begin tag\n" +
        "set $http_path_true  " +
        this.abEditData.aPage +
        ";\n" +
        "set $http_path_false " +
        this.abEditData.bPage +
        ";\n" +
        "set $http_allow_flag 1;\nparameter" +
        "set $http_root_path $http_path_true;\n" +
        "if ($http_allow_flag = 0) {\n" +
        "\tset $http_root_path $http_path_false;\n" +
        "}\n" +
        "root $http_root_path;\n" +
        "location ~* .(htm|html)$ {\n" +
        "\tadd_header Set-Cookie 'H_INDEX_ACCESS=Access-Reject';\n" +
        "\tif ($http_allow_flag = 1) {\n" +
        "\t\tadd_header Set-Cookie 'H_INDEX_ACCESS=Access-Accept';\n" +
        "\t}\n" +
        "}\n" +
        "location ~ ^/ {\n" +
        '\tset $http_access_flag "Access-Reject";\n' +
        '\tif ($http_cookie ~* "H_INDEX_ACCESS=(.+?)(?=;|$)") {\n' +
        "\t\tset $http_access_flag $1;\n" +
        "\t}\n" +
        '\tif ($http_access_flag = "Access-Accept") {\n' +
        "\t\troot $http_path_true;\n" +
        "\t}\n" +
        "}\n" +
        "#access_page end tag\n";
      for (let key in obj) {
        array.push(arr[obj[key]]);
      }
      this.nginxText = template.replace("parameter", array.join(""));
    },
    abchange(value) {
      if (value == 1) {
        this.nginxValue= [0];
        this.nginxText =
          "#access_page begin tag\n" +
          "root " +
          this.abEditData.aPage +
          ";\n" +
          "#access_page end tag\n";
      } else {
        this.nginxText =
          "#access_page begin tag\n" +
          "set $http_path_true  " +
          this.abEditData.aPage +
          ";\n" +
          "set $http_path_false " +
          this.abEditData.bPage +
          ";\n" +
          "set $http_allow_flag 1;\n" +
          "# 如果未检测到百度APP特征码返回假\n" +
          '\tif ($http_user_agent !~* "baiduboxapp") {\n' +
          "\tset $http_allow_flag 0;\n" +
          "}\n" +
          "set $http_root_path $http_path_true;\n" +
          "if ($http_allow_flag = 0) {\n" +
          "\tset $http_root_path $http_path_false;\n" +
          "}\n" +
          "root $http_root_path;\n" +
          "location ~* .(htm|html)$ {\n" +
          "\tadd_header Set-Cookie 'H_INDEX_ACCESS=Access-Reject';\n" +
          "\tif ($http_allow_flag = 1) {\n" +
          "\t\tadd_header Set-Cookie 'H_INDEX_ACCESS=Access-Accept';\n" +
          "\t}\n" +
          "}\n" +
          "location ~ ^/ {\n" +
          '\t\tset $http_access_flag "Access-Reject";\n' +
          '\t\tif ($http_cookie ~* "H_INDEX_ACCESS=(.+?)(?=;|$)") {\n' +
          "\t\tset $http_access_flag $1;\n" +
          "\t}\n" +
          '\t\tif ($http_access_flag = "Access-Accept") {\n' +
          "\t\troot $http_path_true;\n" +
          "\t}\n" +
          "}\n" +
          "#access_page end tag\n";
      }
    },

    nginxSave() {
      this.$confirm("该操作有风险, 请确保AB页路径绝对正确是否继续?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.nginxLoading = true;
          this.$http
            .post("website/saveNginx", {
              id: this.abEditData.id,
              abRadio: this.abRadio,
              nginxText: this.nginxText,
            })
            .then((res) => {
              this.nginxLoading = false;
              if (res.data.code === 0) {
                this.$message({
                  type: "success",
                  message: res.data.msg,
                  dangerouslyUseHTMLString: true,
                });
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((e) => {
              this.nginxLoading = false;
              this.$message.error(e.message);
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
    },
  },
};
</script>

<style scoped>
</style>
